    //
//  RCDataBaseQueue.m
//  RCDataBaseProject
//
//  Created by Roiy on 2017/7/31.
//  Copyright © 2017年 Roiy. All rights reserved.
//

#import "RCDataBaseQueue.h"
#import "RCSQLDataBaseManager.h"
static const void * const rcDispatchQueueSpecificKey = &rcDispatchQueueSpecificKey;

@interface RCDataBaseQueue()
{
    dispatch_queue_t    _queue;
    RCSQLDataBaseManager  *_dataBase;
}
@end

@implementation RCDataBaseQueue

#pragma mark ---Create Current Class
+(instancetype)dataBaseQueueWithPath:(NSString *)dbPath
{
    return  [[self alloc] initWithDataBasePath:dbPath];
}

-(instancetype)initWithDataBasePath:(NSString *)dbPath
{
    _dataBasePath = [dbPath copy];
    _dataBase = [RCSQLDataBaseManager databaseWithPath:dbPath];
    BOOL openHandle = [_dataBase openDB];
    if (!openHandle) {
        NSLog(@"打开数据库失败");
    }
    _queue = dispatch_queue_create([@"test" UTF8String], NULL);
    dispatch_queue_set_specific(_queue, rcDispatchQueueSpecificKey, (__bridge void *)self, NULL);
    return self;
}

#pragma mark --- DataBase Sync\Async Method
-(void)syncDataBaseHandle:(void (^)(RCSQLDataBaseManager *dataBase))block
{
    RCDataBaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(rcDispatchQueueSpecificKey);
    assert(currentSyncQueue != self);
    dispatch_sync(_queue, ^{
        RCSQLDataBaseManager *dataBase = [self createDataBase];
        block(dataBase);
    });
}

-(void)syncDataBaseTransactionHandle:(BOOL)useDeferred withBlock:(void (^)(RCSQLDataBaseManager *dataBase))block
{
    dispatch_sync(_queue, ^() {
        BOOL shouldRollback = NO;
        if (useDeferred) {
            [[self createDataBase] beginDeferredTransaction];
        }
        else {
            [[self createDataBase] beginTransaction];
        }
        block([self createDataBase]);
        if (shouldRollback) {
            [[self createDataBase] rollbackTransaction];
        }
        else {
            [[self createDataBase] commitTransaction];
        }
    });
}

#pragma mark --- Public DataBase Handle--
-(RCSQLDataBaseManager *)createDataBase
{
    if (!_dataBase) {
        _dataBase = [RCSQLDataBaseManager databaseWithPath:_dataBasePath];
    }
    return _dataBase;
}
@end
